<?php

namespace App\Rules;

use Illuminate\Support\Facades\Validator;
class ArrValidator  extends BaseRules
{
    private int $index = 0;  //坐标
    private string $validatorEditor = "";  //错误
    private string $error = "";  //错误收集器

    public function __construct(
        public readonly  array $validator,
        public readonly  int|null $max_count = null,
    ) {
    }


    /**
     * 判断是否通过验证规则
     *
     * @param  string  $attribute 检测的字段
     * @param  mixed   $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if(!array_is_list($value)){
            $this->error  = "必须是list结构的数组";
            return false;
        }
        if($this->max_count !== null && count($value) > $this->max_count ){
            $this->error  = "数组长度不得大于" . $this->max_count;
            return false;
        }

        foreach($value as $key => $val){
            $validator =  Validator::make(
                [
                'val' => $val
            ], [
                'val' => $this->validator
            ] );
            if ($validator->fails()) {
                $this->validatorEditor =   substr( $validator->errors()->first(),3 );
                $this->index = $key ;
                return false;  //数据验证错误
            }
        }
        return true;
    }

    /**
     * 获取校验错误信息
     *
     * @return string
     */
    public function message()
    {
        return  $this->error  ? ":attribute  ". $this->error : ":attribute  下标{$this->index}  {$this->validatorEditor}";
    }
}
